import React, { Component } from 'react'
import { Card, Button, Table, Modal, message } from "antd"
import { formateDate } from '@/utils/dateUtils';
import LinkButton from '@/components/link-button';
import { PAGE_SIZE } from '@/utils/constant';
import { reqDeleteUser, reqUsers, reqAddOrUpdateUser } from '@/api';
import UserForm from './userForm';

/**
 * 用户管理路由
 */
export default class User extends Component {
  constructor(props) {
    super(props)
    this.state = {
      loading: false,
      users: [],  //所有的用户列表
      roles: [],  //所有角色的列表
      isShow: false,   //控制弹窗的显示和关闭
    }
    this.initColumn();
  }

  initColumn = () => {
    this.columns = [
      {
        title: "用户名",
        dataIndex: "username"
      },
      {
        title: "邮箱",
        dataIndex: "email"
      },
      {
        title: "电话",
        dataIndex: "phone"
      },
      {
        title: "注册时间",
        dataIndex: "create_time",
        render: formateDate
      },
      {
        title: "所属角色",
        dataIndex: "role_id",
        // render:(role_id)=>this.state.roles.find(role=>role._id===role_id).name
        render: (role_id) => this.roleNames[role_id]
      },
      {
        title: "操作",
        render: (user) => (
          <span>
            <LinkButton onClick={() => this.updateUser(user)}>修改</LinkButton>
            <LinkButton onClick={() => this.deleteUser(user)}>删除</LinkButton>
          </span>
        )
      },

    ]

  }

  /**
   * 根据roles数组，生成包含所有角色名对象(属性值用角色id的值)
   */

  initRoleNames = (roles) => {
    const roleNames = roles.reduce((pre, role) => {
      pre[role._id] = role.name
      return pre
    }, {})

    //保存起来
    this.roleNames = roleNames
  }

  getUsers = async () => {
    let res = await reqUsers();
    if (res.data.status === 0) {
      const { users, roles } = res.data.data
      this.initRoleNames(roles);
      this.setState({
        users,
        roles
      })
    }
  }
  //添加或者修改用户
  addOrUpdateUser = () => {
    this.setState({ isShow: false })
    //1.收集数据
    this.form.validateFields().then(async (values) => {
      const { username, password, phone, email, role_id } = values;
      const user = { username, password, phone, email, role_id }
      //清除表单的输入的数据
      this.form.resetFields();
      //2.发送请求
      //如果是更新，需要给user指定_id属性
      if(this.user&&this.user._id){
          user._id=this.user._id;
      }
      const result = await reqAddOrUpdateUser(user);
      if (result.data.status === 0) {
        //3.更新列表显示
        message.success(`${this.user?'修改':'添加'}用户成功`);
        this.getUsers();
      }

    })
  }

  updateUser = (user) => {
    this.setState({
      isShow: true
    })
    this.user = user;
  }

  showAdd=()=>{
    this.user=null  //去除前面保存的user
    this.setState({
      isShow: true
    })
  }

  deleteUser = (user) => {
    Modal.confirm({
      title: `确定删除${user.username}吗？`,
      onOk: async () => {
        const res = await reqDeleteUser(user._id);
        if (res.data.status === 0) {
          message.success("删除用户成功！")
          this.getUsers();
        }

      }
    })
  }


  componentDidMount() {
    this.getUsers()
  }

  render() {
    const { loading, users, roles, isShow } = this.state
    const title = <Button type='primary' onClick={this.showAdd}>创建用户</Button>
    const  user  = this.user||{}
    return (
      <Card title={title}>
        <Table
          rowKey="_id"
          loading={loading}
          dataSource={users}
          columns={this.columns}
          pagination={{ defaultPageSize: PAGE_SIZE, showQuickJumper: true }}
        />

        <Modal title={user._id? '修改用户' : "添加用户"} cancelText="取消" okText="确定"
          open={isShow} onOk={this.addOrUpdateUser}
          onCancel={() => this.setState({ isShow: false })}>
          <UserForm  setForm={form => this.form = form} roles={roles} user={user} />
        </Modal>
      </Card>
    )
  }
}
